//
//  HUDSnackbarVC.swift
//  BWPanelKit
//
//  Created by zhuxuhong on 2022/3/7.
//

import UIKit
import BWExtensionKit
import BWToolKit

public class HUDSnackbarVC: HUDVC {
    @IBOutlet weak var wrapperView: UIView!
    @IBOutlet weak var button: UIButton!
    @IBOutlet weak var topCons: NSLayoutConstraint!
    @IBOutlet weak var bottomCons: NSLayoutConstraint!
    
    private var snack: HUD.Snack? {
        return hud as? HUD.Snack
    }
    
    public override func setupHUDView() {
        super.setupHUDView()
        
        guard let snack = snack else {
            return
        }
        
        if let ac = snack.action {
            button.isHidden = false
            button.tintColor = HUD.shared.appearance.tintColor
            button.titleLabel?.font = HUD.shared.appearance.textFont.bold
            button.setImage(ac.icon, for: .normal)
            button.setTitle(ac.title, for: .normal)
            button.bw_tapped{ [weak self] _ in
                guard let self = self else { return }
                self.dismiss{
                    ac.handler?()
                }
            }
        }
        else {
            button.isHidden = true
        }
        
        switch snack.position {
        case .top, .center:
            topCons.isActive = true
            bottomCons.isActive = false
        case .bottom:
            topCons.isActive = false
            bottomCons.isActive = true
        }
    }
    
    public override func setupStyles() {
        super.setupStyles()
        
        contentWrapperView.layer.cornerRadius = 0
        wrapperView.backgroundColor = .clear
    }
    
    private var animateOriginValue: CGFloat {
        let insets = Lets.safeAreaInsets
        if topCons.isActive {
            return -(insets.top + 44)
        }
        return -(insets.bottom + 44)
    }
    
    private var animateConstraint: NSLayoutConstraint {
        return topCons.isActive ? topCons : bottomCons
    }
    
    public override func animateInitial() {
        animateConstraint.constant = animateOriginValue
        wrapperView.alpha = 0
    }
    
    public override func animateHUDView(isIn: Bool) {
        let constant = isIn ? 0 : animateOriginValue
        let duration = isIn ? 0.75 : 0.25
        let alpha: CGFloat = isIn ? 1 : 0
        animateConstraint.constant = constant
        UIView.animate(
            withDuration: duration,
            delay: 0,
            usingSpringWithDamping: isIn ? 0.5 : 1,
            initialSpringVelocity: 1,
            options: [.curveEaseOut],
            animations: {
                self.view.layoutIfNeeded()
                self.wrapperView.alpha = alpha
            },
            completion: animationCompleted(isIn: isIn)
        )
    }
}
